<?php
declare(strict_types=1);
namespace app\api\service\msg;

use app\common\model\MpSubscribe;
use app\common\model\Third;
use app\common\service\MsgService;
use app\common\model\Msg;

class WechatMsg extends MsgService{

    protected $msg_type='wechat';

    //模板列表
    const 模拟模板='111111111111111111111111111111111111';

    protected function sendEvent(Msg $msg): bool
    {
        $config=[
            'appid'=>site_config("weichat.mp_appid"),
            'appsecret'=>site_config("weichat.mp_secret"),
        ];
        // 实例接口
        $wechat = new \WeChat\Template($config);
        // 执行操作
        try{
            $wechat->send(json_decode($msg->content,true));
            return true;
        }catch (\Exception $e){
            $this->error=$e->getMessage();
            return false;
        }
    }


    public static function testMsg($user_id)
    {
        $openid=self::getUserMpOpenid($user_id);
        if(!$openid){
            return;
        }
        $postdata=[
            'touser'=>$openid,
            'template_id'=>self::模拟模板,
            //跳转到h5首页
            //'url'=>request()->domain().'/h5/#/pages/index/index',
            //跳转到小程序
            'miniprogram'=>[
                'appid'=>site_config("uniapp.miniapp_id"),
                'pagepath'=>'/pages/index/index',
            ],
            'data'=>[
                'thing1'=>['value'=>'测试1'],
                'thing2'=>['value'=>'测试2'],
            ]
        ];
        $postdata=json_encode($postdata,JSON_UNESCAPED_UNICODE);
        $service=self::newInstance();
        $service->create($postdata,$user_id);
    }

    private static function getUserMpOpenid($user_id)
    {
        $unionid=Third::where(['user_id'=>$user_id])->value('unionid');
        $openid=MpSubscribe::where(['unionid'=>$unionid])->value('openid');
        return $openid;
    }
}